from django.shortcuts import render
from django.shortcuts import redirect
import pandas as pd
import json
from django.http import HttpResponse
from django.http import JsonResponse


def Login(requests):
    if requests.method == 'GET':
        return render(requests, 'login.html')
    username = requests.POST['username']
    pwd = requests.POST['pwd']
    print('username:', username)
    print('pwd:', pwd)
    # return HttpResponse('ok')

    #读取数据
    tbl_datas = pd.read_excel('t_user.xlsm')
    datas = list(tbl_datas.loc[:, 'username'])

    if username in datas:
        i = datas.index(username)
        passwd = tbl_datas.loc[i,'password']
        real_name = tbl_datas.loc[i, 'names']

        if pwd == str(passwd):
            rep = redirect('/index/')
            #将行为进行cookie存储
            rep.set_cookie("is_login", True)

            # requests.session['is_login'] = True

            #将real_name对象转换。json.dumps() 是把python对象转换成json对象的一个过程，生成的是字符串。
            real_name = json.dumps(real_name)

            rep.set_cookie('real_name', real_name)

            # requests.session['real_name'] = real_name

            return rep
        else:
            info = "密码错误"
            # datas = {'code':103, 'msg':'密码错误，请重新输入', 'data':[]}
    else:

        info = "用户名不存在"
    return render(requests, 'error.html', {"info": info})

    #     datas = {"code":102, "msg":"用户名不存在，请重新输入", 'data':[]}
    # return JsonResponse(datas)


def showIndex(requests):
    #从cookie中获取对应数据
    login_state = requests.COOKIES.get('is_login')

    # login_state = requests.session.get('is_login')

    # if not login_state:
    #     return redirect("/login/")
    #
    #将Json字符串解码成python对象
    real_name = json.loads(requests.COOKIES.get('real_name'))

    # real_name = json.loads(requests.session['real_name'])

    return render(requests, 'index.html', {"real_name": real_name})

# def showTest(requests):
#     return render(requests, 'test.html')
#
# def receives(requests):
#     username = requests.POST['username']
#     pwd = requests.POST['pwd']
#     print("用户名：", username)
#     print("密码：", pwd)
#     datas = {"statu":1, "msg":"login success", "data":[12, 45, 46, 123]}